package com.livepass.android.girlspicks.utils;

import java.io.IOException;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.apache.http.params.HttpProtocolParams;
import org.apache.http.util.EntityUtils;
import org.json.JSONException;
import org.json.JSONObject;

import android.content.Context;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageManager;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.util.Log;

public class Utilities {

	public static final int TIME_OUT = 30000;
	public static final int SOCKET_TIME_OUT = 30000;

	public static boolean isNetworkAvailable(Context context) {
		ConnectivityManager connectivity = (ConnectivityManager) context
				.getSystemService(Context.CONNECTIVITY_SERVICE);
		if (connectivity != null) {
			NetworkInfo[] info = connectivity.getAllNetworkInfo();
			if (info != null) {
				for (int i = 0; i < info.length; i++) {
					if (info[i].getState() == NetworkInfo.State.CONNECTED) {
						return true;
					}
				}
			}
		}
		return false;
	}

	public static String callWS(String request, String soapAction) {

		final DefaultHttpClient httpClient = new DefaultHttpClient();
		// request parameters
		HttpParams params = httpClient.getParams();
		HttpConnectionParams.setConnectionTimeout(params, 10000);
		HttpConnectionParams.setSoTimeout(params, 15000);
		// set parameter
		HttpProtocolParams.setUseExpectContinue(httpClient.getParams(), true);

		// POST the envelope
		HttpPost httppost = new HttpPost("http://54.169.10.216/api");
		// add headers
		httppost.setHeader("SoapAction", soapAction);
		httppost.setHeader("Content-Type", "text/xml; charset=utf-8");

		String responseString = "";
		try {

			// the entity holds the request
			HttpEntity entity = new StringEntity(request);
			httppost.setEntity(entity);

			// Response handler
			ResponseHandler<String> rh = new ResponseHandler<String>() {
				// invoked when client receives response
				public String handleResponse(HttpResponse response)
						throws ClientProtocolException, IOException {

					// get response entity
					HttpEntity entity = response.getEntity();

					// read the response as byte array
					StringBuffer out = new StringBuffer();
					byte[] b = EntityUtils.toByteArray(entity);

					// write the response byte array to a string buffer
					out.append(new String(b, 0, b.length));
					return out.toString();
				}
			};
			responseString = httpClient.execute(httppost, rh);
		} catch (Exception e) {
			Log.v("Exception", e.toString());
		}
		// close the connection
		httpClient.getConnectionManager().shutdown();
		Log.i("Webservice", responseString);
		return responseString;
	}

	/*
	 * public static String doRequest(String url) throws
	 * ClientProtocolException, IOException { HttpParams httpParameters = new
	 * BasicHttpParams();
	 * HttpConnectionParams.setConnectionTimeout(httpParameters, TIME_OUT);
	 * HttpConnectionParams.setSoTimeout(httpParameters, SOCKET_TIME_OUT);
	 * HttpClient client = new DefaultHttpClient(httpParameters); HttpGet method
	 * = new HttpGet(url); HttpResponse response = client.execute(method); //
	 * result= response.getEntity().getContent(); String result =
	 * EntityUtils.toString(response.getEntity(), "UTF-8"); return result; }
	 */

	public static JSONObject doPostRequest(String url,
			Map<String, String> params) throws ClientProtocolException,
			IOException, JSONException {
		HttpParams httpParameters = new BasicHttpParams();
		HttpConnectionParams.setConnectionTimeout(httpParameters, TIME_OUT);
		HttpConnectionParams.setSoTimeout(httpParameters, SOCKET_TIME_OUT);
		HttpClient client = new DefaultHttpClient(httpParameters);

		List<NameValuePair> parameters = new LinkedList<NameValuePair>();
		for (String key : params.keySet()) {
			parameters.add(new BasicNameValuePair(key, params.get(key)));
		}

		HttpPost method = new HttpPost(url);
		method.setParams(httpParameters);
		method.setEntity(new UrlEncodedFormEntity(parameters, "UTF-8"));

		HttpResponse response = client.execute(method);
		// result= response.getEntity().getContent();
		String result = EntityUtils.toString(response.getEntity(), "UTF-8");
		JSONObject jsonObject = null;
		jsonObject = new JSONObject(result);
		return jsonObject;
	}

	/*
	 * public static String doRequest(String url, Map<String, String> headers)
	 * throws ClientProtocolException, IOException { HttpParams httpParameters =
	 * new BasicHttpParams();
	 * HttpConnectionParams.setConnectionTimeout(httpParameters, TIME_OUT);
	 * HttpConnectionParams.setSoTimeout(httpParameters, SOCKET_TIME_OUT);
	 * HttpClient client = new DefaultHttpClient(httpParameters); HttpGet method
	 * = new HttpGet(url);
	 * 
	 * // put Headers if (headers != null) { Header[] methodHeaders = new
	 * Header[headers.size()]; int i = 0;
	 * 
	 * for (String key : headers.keySet()) { methodHeaders[i] = new
	 * BasicHeader(key, headers.get(key)); i++; }
	 * method.setHeaders(methodHeaders); }
	 * 
	 * HttpResponse response = client.execute(method); // result=
	 * response.getEntity().getContent(); String result =
	 * EntityUtils.toString(response.getEntity(), "UTF-8"); return result; }
	 * 
	 * public static String doPostRequest(String url, Map<String, String>
	 * params, Map<String, String> headers) throws ClientProtocolException,
	 * IOException { HttpParams httpParameters = new BasicHttpParams();
	 * HttpConnectionParams.setConnectionTimeout(httpParameters, TIME_OUT);
	 * HttpConnectionParams.setSoTimeout(httpParameters, SOCKET_TIME_OUT);
	 * HttpClient client = new DefaultHttpClient(httpParameters);
	 * 
	 * List<NameValuePair> parameters = new LinkedList<NameValuePair>(); for
	 * (String key : params.keySet()) { parameters.add(new
	 * BasicNameValuePair(key, params.get(key))); }
	 * 
	 * HttpPost method = new HttpPost(url); method.setParams(httpParameters);
	 * 
	 * // put Headers if (headers != null) { Header[] methodHeaders = new
	 * Header[headers.size()]; int i = 0;
	 * 
	 * for (String key : headers.keySet()) { methodHeaders[i] = new
	 * BasicHeader(key, headers.get(key)); i++; }
	 * method.setHeaders(methodHeaders); }
	 * 
	 * method.setEntity(new UrlEncodedFormEntity(parameters, "UTF-8"));
	 * 
	 * HttpResponse response = client.execute(method); // result=
	 * response.getEntity().getContent(); String result =
	 * EntityUtils.toString(response.getEntity(), "UTF-8"); return result; }
	 * 
	 * public static String doPostRequest(String url, String data, Map<String,
	 * String> headers) throws ClientProtocolException, IOException { HttpParams
	 * httpParameters = new BasicHttpParams();
	 * HttpConnectionParams.setConnectionTimeout(httpParameters, TIME_OUT);
	 * HttpConnectionParams.setSoTimeout(httpParameters, SOCKET_TIME_OUT);
	 * HttpClient client = new DefaultHttpClient(httpParameters);
	 * 
	 * HttpPost method = new HttpPost(url); method.setParams(httpParameters);
	 * 
	 * // put Headers if (headers != null) { Header[] methodHeaders = new
	 * Header[headers.size()]; int i = 0;
	 * 
	 * for (String key : headers.keySet()) { methodHeaders[i] = new
	 * BasicHeader(key, headers.get(key)); i++; }
	 * method.setHeaders(methodHeaders); }
	 * 
	 * method.setEntity(new ByteArrayEntity(data.getBytes()));
	 * 
	 * HttpResponse response = client.execute(method); // result=
	 * response.getEntity().getContent(); String result =
	 * EntityUtils.toString(response.getEntity(), "UTF-8"); return result; }
	 * 
	 * public static String doPutRequest(String url, Map<String, String> params,
	 * Map<String, String> headers) throws ClientProtocolException, IOException
	 * { HttpParams httpParameters = new BasicHttpParams();
	 * HttpConnectionParams.setConnectionTimeout(httpParameters, TIME_OUT);
	 * HttpConnectionParams.setSoTimeout(httpParameters, SOCKET_TIME_OUT);
	 * HttpClient client = new DefaultHttpClient(httpParameters);
	 * 
	 * List<NameValuePair> parameters = new LinkedList<NameValuePair>(); for
	 * (String key : params.keySet()) { parameters.add(new
	 * BasicNameValuePair(key, params.get(key))); }
	 * 
	 * HttpPut method = new HttpPut(url); method.setParams(httpParameters);
	 * 
	 * // put Headers if (headers != null) { Header[] methodHeaders = new
	 * Header[headers.size()]; int i = 0;
	 * 
	 * for (String key : headers.keySet()) { methodHeaders[i] = new
	 * BasicHeader(key, headers.get(key)); i++; }
	 * method.setHeaders(methodHeaders); }
	 * 
	 * method.setEntity(new UrlEncodedFormEntity(parameters, "UTF-8"));
	 * 
	 * HttpResponse response = client.execute(method); // result=
	 * response.getEntity().getContent(); String result =
	 * EntityUtils.toString(response.getEntity(), "UTF-8"); return result; }
	 * 
	 * public static String doDeleteRequest(String url, Map<String, String>
	 * params, Map<String, String> headers) throws ClientProtocolException,
	 * IOException { HttpParams httpParameters = new BasicHttpParams();
	 * HttpConnectionParams.setConnectionTimeout(httpParameters, TIME_OUT);
	 * HttpConnectionParams.setSoTimeout(httpParameters, SOCKET_TIME_OUT);
	 * HttpClient client = new DefaultHttpClient(httpParameters);
	 * 
	 * HttpPost method = new HttpPost(url) {
	 * 
	 * @Override public String getMethod() { return "DELETE"; } };
	 * 
	 * if (headers != null) { for (String key : headers.keySet()) {
	 * method.addHeader(key, headers.get(key)); } }
	 * 
	 * List<NameValuePair> parameters = new LinkedList<NameValuePair>(); for
	 * (String key : params.keySet()) { parameters.add(new
	 * BasicNameValuePair(key, params.get(key))); }
	 * 
	 * method.setParams(httpParameters);
	 * 
	 * method.setEntity(new UrlEncodedFormEntity(parameters, "UTF-8"));
	 * 
	 * HttpResponse response = client.execute(method); // result=
	 * response.getEntity().getContent(); String result =
	 * EntityUtils.toString(response.getEntity(), "UTF-8"); return result; }
	 */

	/**
	 * Check package name exist
	 * 
	 * @param targetPackage
	 * @return
	 */
	public static boolean isPackageExisted(Context context, String targetPackage) {
		List<ApplicationInfo> packages;
		PackageManager pm = context.getPackageManager();
		packages = pm.getInstalledApplications(0);
		for (ApplicationInfo packageInfo : packages) {
			if (packageInfo.packageName.equals(targetPackage))
				return true;
		}
		return false;
	}

	/**
	 * VuVT1
	 * 
	 * @param datetimeFrom
	 * @return japan date time
	 */
	public static String convertToStandardTime(String datetimeFrom) {
		String year = datetimeFrom.substring(0, 4);
		String month = datetimeFrom.substring(5, 7);
		String day = datetimeFrom.substring(8, 10);
		String time = datetimeFrom.substring(11, 19);
		return year + "年" + month + "月" + day + "日 " + time;
	}
}
